package com.pig4cloud.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.pig4cloud.entity.UserEntity;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.xml.bind.DatatypeConverter;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.time.LocalDateTime;

/**
 * @Author: oliver
 * @CreateTime: 2023-12-7
 * @Description: 令牌工具类
 * @Version: 1.0
 */
public class JwtUtil {

	/**
	 * 过期时间
	 **/
	public static final long EXPIRE_TIME = 1000 * 60 * 60 * 24 * 7;
	public static final String USER_INFO = "userInfo";
	/**
	 * shu_zhi_farm_program
	 **/
	private static final String TOKEN_KEY = "8b522922b5d9261f1f35c4bc569488c9b22e89dfshuzhifarmminiprogram";

	/**
	 * 令牌数据解析
	 *
	 * @param token: 令牌
	 * @return io.jsonwebtoken.Claims
	 * @Date 2023/2/23 11:07
	 * @Author Oliver
	 **/
	public static UserEntity parseToken(String token) {
		if (StrUtil.isBlank(token)) {
			return null;
		}
		try {
			return JSONUtil.toBean(JSONUtil.parse(Jwts.parser()
							.setSigningKey(DatatypeConverter.parseBase64Binary(TOKEN_KEY))
							.parseClaimsJws(token).getBody().get(USER_INFO))
					.toJSONString(0), UserEntity.class);
		} catch (Exception ex) {
			throw new RuntimeException(ex.getMessage());
		}
	}

	/**
	 * 生成token
	 *
	 * @param userInfo: 用户信息
	 * @return java.lang.String
	 * @Date 2023/2/23 11:25
	 * @Author Oliver
	 **/
	public static String createToken(UserEntity userInfo) {
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
		//生成签名密钥
		byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(TOKEN_KEY);

		Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
		//添加构成JWT的参数
		JwtBuilder builder = Jwts.builder()
				// 设置载荷信息
				.claim(USER_INFO, JSONUtil.parse(userInfo).toJSONString(0))
				// token 超时时间
				.setExpiration(DateUtil.parse(LocalDateTime.now()
						.plusSeconds(EXPIRE_TIME).toString()))
				.signWith(SignatureAlgorithm.HS256, signingKey);

		//生成JWT
		return builder.compact();
	}

	public static boolean checkToken(String jwtToken) {
		if (StrUtil.isEmpty(jwtToken)) {
			return false;
		}
		try {
			Jwts.parser().setSigningKey(TOKEN_KEY).parseClaimsJws(jwtToken);
		} catch (Exception e) {
			return false;
		}
		return true;
	}
}
